package cn.qingxuntech.console.controller

import cn.dev33.satoken.stp.StpUtil
import cn.qingxuntech.console.model.R
import cn.qingxuntech.console.model.request.LoginRequest
import cn.qingxuntech.console.model.response.AccountResponse
import cn.qingxuntech.console.service.AccountService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/qx/console/v1/account")
class LoginController {
    @Autowired
    lateinit var accountService: AccountService

    @PostMapping("/login")
    fun login(@RequestBody loginRequest: LoginRequest): R<AccountResponse>? {
        val account = accountService.login(loginRequest.loginName, loginRequest.loginPassword)

        if (account == null) {
            return R.fail("账户或密码错误")
        }

        StpUtil.login(account.id)

        account.loginPassword = null
        return R.success(AccountResponse().apply {
            this.account = account
            this.token = StpUtil.getTokenValue()
        })
    }

}
